//
//  DrawingViewController.m
//  YSSmartHome
//
//  Created by Yahaong on 16/8/11.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "DrawingViewController.h"
#import "DataManager.h"
#import "DeviceCollectionViewCell.h"
#import "HomeCollectionViewTopView.h"
#import "DeviceControlController.h"
#import "ZTLCCamera.h"
#import "LiveVideoViewController.h"
#import "OpenApiService.h"
#import "ZTUser.h"
#import "CameraDeviceInfo.h"
#import "DeviceEditController.h"
#import "ZTLCCameraUtil.h"
#import "AirMonitoringController.h"
#import "YSCommon.h"

static CGFloat const margin = 5.0f;
@interface DrawingViewController ()
<
UICollectionViewDelegate,
UICollectionViewDataSource
>
@property (nonatomic, strong) UICollectionView *contentView;
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) HomeCollectionViewTopView *topView;
@property (nonatomic, strong) NSIndexPath *originalIndexPath;

@end

@implementation DrawingViewController

#pragma mark - life cycle

- (void)dealloc {
    debugLogInfo(@"DrawingViewController  dealloc");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSubViews];
    [self addGesture];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(removeDev) name:@"kZTRemoveDeviceNotifKey" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(openCameral:) name:@"open" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(editDeviceNotificationHandle) name:@"kZTHomeEditDeviceNotifKey" object:nil];
}


#pragma mark - event response
- (void)zt_tap:(UITapGestureRecognizer *)tap {
    if (self.originalIndexPath) {
        DeviceCollectionViewCell *originalCell = (DeviceCollectionViewCell *)[self.contentView cellForItemAtIndexPath:self.originalIndexPath];
        originalCell.isEditOrDel = NO;
        self.originalIndexPath = nil;
    } else {
        NSIndexPath *currentIndex = [self.contentView indexPathForItemAtPoint:[tap locationOfTouch:0 inView:self.contentView]];
        if (currentIndex) {
            [self collectionView:self.contentView didSelectItemAtIndexPath:currentIndex];
        }
    }
}

- (void)zt_longPressed:(UILongPressGestureRecognizer *)longPressGesture {
    if (longPressGesture.state == UIGestureRecognizerStateBegan) {
        NSIndexPath* currentIndexPath = [self.contentView indexPathForItemAtPoint:[longPressGesture locationOfTouch:0 inView:longPressGesture.view]];
        if (self.originalIndexPath != nil &&  self.originalIndexPath != currentIndexPath) {
            DeviceCollectionViewCell *originalCell = (DeviceCollectionViewCell *)[self.contentView cellForItemAtIndexPath:self.originalIndexPath];
            originalCell.isEditOrDel = NO;
        }
        DeviceCollectionViewCell *cell = (DeviceCollectionViewCell *)[self.contentView cellForItemAtIndexPath:currentIndexPath];
        cell.isEditOrDel = YES;
        self.originalIndexPath = currentIndexPath;
    }
}

#pragma mark - private method

- (void)addGesture {
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(zt_longPressed:)];
    [self.contentView addGestureRecognizer:longPress];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(zt_tap:)];
    [self.contentView addGestureRecognizer:tap];
}

- (void)initSubViews {
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = kBgColor;
    [self.view addSubview:self.contentView];
    [self layoutPageSubViews];
}

- (void)layoutPageSubViews {
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        CGFloat egesMagin = margin * 2;
        make.edges.equalTo(self.view).offset(UIEdgeInsetsMake(egesMagin, egesMagin, 0, egesMagin));
    }];
}

- (BOOL)checkIsCameraAndUnbind:(ZTDevice *)dev {
    BOOL result = true;
    if (dev.devType == ZTDeviceTypeLCCamera)
    {
        ZTLCCamera *lCCamera = (ZTLCCamera *)dev;
        result = [lCCamera unbundling];
    }
    return result;
}

- (void)delDevice:(NSIndexPath *)indexPath {
    ZTDevice *device = self.dataSource[indexPath.row];
    if (![self checkIsCameraAndUnbind:device]) {
        return;
    }
    NSMutableArray* array = [NSMutableArray array];
    XAITYPEAPSN apsn = device.apsn;
    XAITYPELUID luid = device.luid;
    XAITLV* tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_APSN bytes:&apsn length:sizeof(apsn)];
    [array addObject:tlv];
    tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_LUID bytes:&luid length:sizeof(luid)];
    [array addObject:tlv];
    NSError* error = [kMQTTSessionManager.xai  sendCMD:0x01 toApsn:kMQTTSessionManager.currentUser.currentBindApsn toLuid:kGATEWAYLUID datas:array];
    if (error.code == 0) {
        debugLogInfo(@"删除成功");
    } else {
        debugLogInfo(@"删除失败%@",error.localizedDescription);
    }
}

- (void)removeDev {
    if (self.originalIndexPath != nil) {
        DeviceCollectionViewCell *originalCell = (DeviceCollectionViewCell *)[self.contentView cellForItemAtIndexPath:self.originalIndexPath];
        originalCell.isEditOrDel = NO;
        [self delDevice:self.originalIndexPath];
        self.originalIndexPath = nil;
    }
}

- (void)editDeviceNotificationHandle {
    if (self.originalIndexPath != nil) {
        DeviceEditController *deviceEditVc = [[DeviceEditController alloc]init];
        deviceEditVc.device = self.dataSource[self.originalIndexPath.item] ;
        deviceEditVc.fromMe = true;
        [self.navigationController pushViewController:deviceEditVc animated:YES];
        DeviceCollectionViewCell *cell = (DeviceCollectionViewCell *)[self.contentView cellForItemAtIndexPath:self.originalIndexPath];
        cell.isEditOrDel = NO;
        self.originalIndexPath = nil;
    }
}

- (void)openCameral:(NSNotification *)notify {
    ZTLCCamera *cameral = (ZTLCCamera *)notify.object;
    [ZTLCCameraUtil onLive:cameral controller:self];
}
    
#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    DeviceCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([self class]) forIndexPath:indexPath];
    if (indexPath.item >= self.dataSource.count) {
        debugLogInfo(@"data数据越界了啊。。。。。。。。。。。。。");
    } else {
        cell.dev = self.dataSource[indexPath.item];
    }
    cell.isEditOrDel = NO;
    return cell;
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView *reusableview = nil;
    if (kind == UICollectionElementKindSectionHeader) {
        HomeCollectionViewTopView *header = (HomeCollectionViewTopView *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeadView" forIndexPath:indexPath];
        if ([self.navigationItem.title isEqualToString:@"客厅"]) {
            header.imageStr = @"home_top_parlor";
        }
        else if ([self.navigationItem.title isEqualToString:@"卧室"]) {
            header.imageStr = @"home_top_bedroom";
        }
        else if ([self.navigationItem.title isEqualToString:@"书房"]) {
            header.imageStr = @"home_top_study";
        }
        else {
            header.imageStr = @"home_top_other";
        }
        reusableview = header;
    }
    return reusableview;
}

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZTDevice *device =  self.dataSource[indexPath.item];
    if (device.devType == ZTDeviceTypeLCCamera) {
        ZTLCCamera *lcCamera = (ZTLCCamera *)device;
        [ZTLCCameraUtil onLive:lcCamera controller:self];
    } else if (device.devType == ZTDeviceTypeAir)
    {
        AirMonitoringController* airMonitoringVc = [[AirMonitoringController alloc]init];
        airMonitoringVc.device = (ZTAirMonitorDevice *) device;
        [self.navigationController pushViewController:airMonitoringVc animated:YES];
    } else {
        DeviceControlController *vc = [[DeviceControlController alloc]init];
        vc.device = device;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - private method

- (void)dataRefresh {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableArray* devs = [NSMutableArray array];
        [kDataManager devlistLock];
        for (ZTDevice* dev in kDataManager.deviceListenList) {
            if (dev.apsn != kMQTTSessionManager.currentUser.currentBindApsn) {
                continue;
            }
            NSString* devRoom = [dev getRoomName];
            if ([devRoom isEqualToString:self.title]) {
                [devs addObject:dev];
            } else {
                if (self.index == 0) {
                    if ([devRoom isEqualToString:@"unknow"]) {
                        [devs addObject:dev];
                    }
                }
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            self.dataSource = devs;
            if (self.originalIndexPath){
                DeviceCollectionViewCell *originalCell = (DeviceCollectionViewCell *)[self.contentView cellForItemAtIndexPath:self.originalIndexPath];
                originalCell.isEditOrDel = NO;
                self.originalIndexPath = nil;
            }
            [self.contentView reloadData];
        });
        [kDataManager devlistUnlock];
    });
}


#pragma mark - getters and setters

- (UICollectionViewFlowLayout *)flowLayout
{
    if (!_flowLayout) {
        _flowLayout = [[UICollectionViewFlowLayout alloc]init];
        _flowLayout.minimumLineSpacing = margin;
        _flowLayout.minimumInteritemSpacing = margin;
        CGFloat width = (kScreenWidth - margin * 6) / 3;
        CGFloat height = width * 0.912;
        _flowLayout.itemSize = CGSizeMake(width, height);
        _flowLayout.headerReferenceSize = CGSizeMake(kScreenWidth, kIphoneSize_Height(177));
        [_flowLayout setHeaderReferenceSize: CGSizeMake(kScreenWidth, kIphoneSize_Height(177))];
    }
    return _flowLayout;
}
- (UICollectionView *)contentView
{
    if (!_contentView) {
        _contentView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:self.flowLayout];
        _contentView.backgroundColor = kBgColor;
        _contentView.pagingEnabled = YES;
        _contentView.bounces = NO;
        _contentView.delegate = self;
        _contentView.dataSource = self;
        _contentView.showsVerticalScrollIndicator = NO;
        _contentView.showsHorizontalScrollIndicator = NO;
        [_contentView registerClass:[DeviceCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([self class])];
        [_contentView registerClass:[HomeCollectionViewTopView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeadView"];
    }
    return _contentView;
}

- (HomeCollectionViewTopView *)topView
{
    if (!_topView) {
        _topView = [[HomeCollectionViewTopView alloc]init];
        _topView.imageStr = @"home_top";
    }
    return _topView;
}
@end
